import axios from 'axios'

const BASE_URL = 'http://localhost:8080'

export const chatWithAIStream = (question, conversationId, onMessage, onError, onComplete) => {
  const url = `${BASE_URL}/dashscope/chat?question=${encodeURIComponent(question)}&conversationId=${encodeURIComponent(conversationId)}`
  const eventSource = new EventSource(url)

  eventSource.onmessage = (event) => {
    if (event.data && event.data.trim()) {
      onMessage(event.data)
    }
  }

  eventSource.onerror = (err) => {
    eventSource.close()
    if (onError) onError(err)
    if (onComplete) onComplete()
  }

  // 检测流结束的方法
  const originalClose = eventSource.close.bind(eventSource)
  eventSource.close = () => {
    originalClose()
    if (onComplete) onComplete()
  }

  return eventSource
}

// 获取对话ID列表
export const getConversationIds = async () => {
  try {
    const response = await axios.get(`${BASE_URL}/dashscope/conversation/ids`)
    return response.data
  } catch (error) {
    console.error('获取对话ID列表失败:', error)
    throw error
  }
}

// 获取指定对话ID的聊天历史
export const getChatHistory = async (conversationId) => {
  try {
    const response = await axios.get(`${BASE_URL}/dashscope/conversation/history/${conversationId}`)
    return response.data
  } catch (error) {
    console.error('获取聊天历史失败:', error)
    throw error
  }
}

// 删除指定对话ID的聊天记录
export const deleteConversation = async (conversationId) => {
  try {
    const response = await axios.get(`${BASE_URL}/dashscope/conversation/delete/${conversationId}`)
    return response.data
  } catch (error) {
    console.error('删除对话失败:', error)
    throw error
  }
}
